#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将处理后的结果文件（jsonl或json）中的before/after内容导出为txt，便于直观对比。
每个unit导出格式：
==== PR:xxx File:xxx ====
[TYPE: add/delete/modify]
[CONTEXT BEFORE]
xxx
[CHANGES]
BEFORE: xxx
AFTER: xxx
[CONTEXT AFTER]
xxx
------------------------
"""
import os
import sys
import json

def export_diff_txt(input_file, output_txt):
    units = []
    if input_file.endswith('.jsonl'):
        with open(input_file, 'r', encoding='utf-8') as f:
            for line in f:
                if line.strip():
                    units.append(json.loads(line))
    elif input_file.endswith('.json'):
        with open(input_file, 'r', encoding='utf-8') as f:
            units = json.load(f)
    else:
        print(f"不支持的文件格式: {input_file}")
        return

    with open(output_txt, 'w', encoding='utf-8') as out:
        for unit in units:
            pr_number = unit.get('pr_number', '')
            file_path = unit.get('file_path', '')
            change_type = unit.get('change_type', 'unknown')
            before = unit.get('remove_content', '')
            after = unit.get('add_content', '')
            context_before = unit.get('context_before', '')
            context_after = unit.get('context_after', '')
            
            out.write(f"==== PR:{pr_number} File:{file_path} ====" + "\n")
            out.write(f"[TYPE: {change_type}]" + "\n")
            
            # 添加上下文信息
            if context_before.strip():
                out.write("[CONTEXT BEFORE]\n")
                out.write(context_before.strip() + "\n")
            
            out.write("[CHANGES]\n")
            out.write("BEFORE: " + before.strip() + "\n")
            out.write("AFTER: " + after.strip() + "\n")
            
            if context_after.strip():
                out.write("[CONTEXT AFTER]\n")
                out.write(context_after.strip() + "\n")
            
            out.write("------------------------\n\n")
    print(f"已导出对比txt: {output_txt}")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("用法: python diff_txt_export.py <input_jsonl/json> <output_txt>")
        sys.exit(1)
    export_diff_txt(sys.argv[1], sys.argv[2]) 